export default {
  data() {
    return {
      searchForm: {},
      listPagination: {
        isListRefreshIng: false,
        isListLoading: false,
        isListFinished: false,
        isFetching: false,
        isListLoadingError: false,
        data: [],
        current: 1,
        pageSize: 15
      }
    }
  },
  methods: {
    onSearchBefore() {},
    onSearch() {
      this.onSearchBefore()
      this.onListRefresh()
    },
    fetchListData() {
      if (this.listPagination.isFetching) {
        console.warn('fetchListData loading...')
        return
      } else {
        this.listPagination.isFetching = true
      }
      let params = {
        ...this.searchForm,
        curPage: this.listPagination.current,
        length: this.listPagination.pageSize
      }
      return this.request(params)
        .then(res => {
          let resData = res.data.data
          if (!Array.isArray(resData)) {
            resData = resData.list || resData
          }
          if (this.resultDataKey) {
            resData = resData[this.resultDataKey]
          }
          if (
            this.resultDataFormatter &&
            typeof this.resultDataFormatter === 'function'
          ) {
            resData = this.resultDataFormatter(resData)
          }
          if (this.listPagination.isListRefreshIng) {
            this.listPagination.data = []
            this.listPagination.isListRefreshIng = false
          }
          if (this.listPagination.current == 1) {
            this.listPagination.data = resData
          } else {
            this.listPagination.data = this.listPagination.data.concat(resData)
          }
          if (this.listPagination.isListLoading) {
            this.listPagination.isListLoading = false
          }
          if (this.listPagination.pageSize > resData.length) {
            this.listPagination.isListFinished = true
          } else {
            this.listPagination.current++
          }
          if (this.listPagination.isFetching) {
            this.listPagination.isFetching = false
          }

          this.$emit('onListDataChange', this.listPagination.data)
        })
        .catch(() => {
          this.listPagination.isListLoadingError = true
          if (this.listPagination.isListRefreshIng) {
            this.listPagination.isListRefreshIng = false
          }
          if (this.listPagination.isListLoading) {
            this.listPagination.isListLoading = false
          }
          if (this.listPagination.isFetching) {
            this.listPagination.isFetching = false
          }
        })
    },
    onListLoad() {
      // this.listPagination.isListLoading = true
      this.fetchListData()
    },
    onListRefresh() {
      this.listPagination.current = 1
      // this.listPagination.isListRefreshIng = true
      this.listPagination.isListFinished = false
      this.listPagination.isListLoading = true
      this.fetchListData()
    }
  }
}
